import React from 'react';
import { Card, Form, Input, Upload, Modal, Button, Row, Col, Space, message } from 'antd';
import { PlusOutlined, UploadOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import Link from '@tiptap/extension-link';

// 推广配置页（模仿 admin-web 的 Promote/Config.vue）
export default function PromoteConfig() {
  const [form] = Form.useForm();
  const [setting, setSetting] = React.useState({
    logo: '',
    icon: '',
    homeSignImg: '',
    homeBackImg: '',
    homeDownImg: '',
    equipmentAnimation: '',
    logoUrl: '',
    homeDownText: ''
  });

  // 各上传区域的文件列表（限制为 1 个）
  const [logoList, setLogoList] = React.useState([]);
  const [iconList, setIconList] = React.useState([]);
  const [homeSignImgList, setHomeSignImgList] = React.useState([]);
  const [homeBackImgList, setHomeBackImgList] = React.useState([]);
  const [homeDownImgList, setHomeDownImgList] = React.useState([]);
  const [equipmentAnimationList, setEquipmentAnimationList] = React.useState([]);

  const [tipsOpen, setTipsOpen] = React.useState(false);
  const [tipsText, setTipsText] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  // Tiptap 编辑器：以 setting.homeDownText 作为初始内容
  const editor = useEditor({
    extensions: [
      StarterKit,
      Underline,
      Link.configure({ openOnClick: true })
    ],
    content: setting.homeDownText || '',
    onUpdate: ({ editor }) => {
      const html = editor.getHTML();
      setSetting((s) => ({ ...s, homeDownText: html }));
    },
  });

  // 当从 localStorage 恢复数据后，同步到编辑器
  React.useEffect(() => {
    if (!editor) return;
    const current = editor.getHTML();
    const next = setting.homeDownText || '';
    if (current !== next) {
      editor.commands.setContent(next);
    }
  }, [editor, setting.homeDownText]);

  // 统一的本地处理上传（不走后端，直接预览并写入 setting 字段）
  const handleBeforeUpload = (file, field, setter) => {
    const url = URL.createObjectURL(file);
    const item = { uid: String(Date.now()), name: file.name, status: 'done', url, originFileObj: file };
    setter([item]);
    setSetting((s) => ({ ...s, [field]: url }));
    return false; // 阻止 antd 自动上传
  };

  const handleRemove = (field, setter) => {
    setter([]);
    setSetting((s) => ({ ...s, [field]: '' }));
  };

  const onInputChange = (field, e) => {
    const value = e?.target ? e.target.value : e;
    setSetting((s) => ({ ...s, [field]: value }));
  };

  const showTips = (text) => {
    setTipsText(text);
    setTipsOpen(true);
  };

  const submitForm = async () => {
    try {
      setSaving(true);
      // 这里模拟保存动作：写入 localStorage 以便演示
      localStorage.setItem('promoteConfig', JSON.stringify(setting));
      message.success('推广配置已保存（本地演示存储）');
    } catch (e) {
      message.error('保存失败：' + (e?.message || '未知错误'));
    } finally {
      setSaving(false);
    }
  };

  // 页面初始化：尝试从 localStorage 读取演示数据
  React.useEffect(() => {
    try {
      const raw = localStorage.getItem('promoteConfig');
      if (raw) {
        const cfg = JSON.parse(raw);
        setSetting(cfg || {});
        // 恢复文件列表用于预览（演示用途）
        const toItem = (u, n) => (u ? [{ uid: String(Date.now()), name: n || '已上传', status: 'done', url: u }] : []);
        setLogoList(toItem(cfg.logo, 'logo'));
        setIconList(toItem(cfg.icon, 'icon'));
        setHomeSignImgList(toItem(cfg.homeSignImg, 'homeSignImg'));
        setHomeBackImgList(toItem(cfg.homeBackImg, 'homeBackImg'));
        setHomeDownImgList(toItem(cfg.homeDownImg, 'homeDownImg'));
        setEquipmentAnimationList(toItem(cfg.equipmentAnimation, 'equipment.zip'));
      }
    } catch {}
  }, []);

  // 通用上传按钮（图片）
  const renderPictureUpload = (label, field, fileList, setter, accept, sizeHint, tipsIndex) => (
    <div style={{ display: 'flow-root' }}>
      <div style={{ marginRight: 8 }}>
        <div>{label}</div>
        <div onClick={() => showTips(sizeHint)} style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
          <InfoCircleOutlined style={{ fontSize: 13, marginRight: 4, color: '#02a7f0' }} />
          <span style={{ fontSize: 12, color: '#02a7f0' }}>说明</span>
        </div>
      </div>
      <Form.Item style={{ marginBottom: 5, marginTop: 5 }}>
        <Upload
          listType="picture-card"
          fileList={fileList}
          accept={accept}
          maxCount={1}
          onRemove={() => handleRemove(field, setter)}
          beforeUpload={(file) => handleBeforeUpload(file, field, setter)}
        >
          {fileList && fileList.length >= 1 ? null : (
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>上传</div>
            </div>
          )}
        </Upload>
      </Form.Item>
      <div style={{ color: 'red', fontSize: 12 }}>{sizeHint}</div>
    </div>
  );

  return (
    <Card title="推广配置" bordered>
      <Form form={form} layout="vertical" initialValues={setting}>
        {/* 第一行：logo、icon、homeSignImg、homeBackImg */}
        <Row gutter={20} style={{ marginBottom: 20 }}>
          <Col span={6}>
            {renderPictureUpload('平台 Logo', 'logo', logoList, setLogoList, '.jpg,.png', '建议尺寸：200px × 52px', 1)}
          </Col>
          <Col span={6}>
            {renderPictureUpload('网站图标（favicon）', 'icon', iconList, setIconList, '.ico', '建议尺寸：52px × 52px', 2)}
          </Col>
          <Col span={6}>
            {renderPictureUpload('首页标识图', 'homeSignImg', homeSignImgList, setHomeSignImgList, '.jpg,.png', '建议尺寸：500px × 378px', 3)}
          </Col>
          <Col span={6}>
            {renderPictureUpload('首页背景图', 'homeBackImg', homeBackImgList, setHomeBackImgList, '.jpg,.png', '建议尺寸：1920px × 1080px', 4)}
          </Col>
        </Row>

        {/* 第二行：设备动画（zip）、底部 Logo */}
        <Row gutter={20} style={{ marginBottom: 20 }}>
          <Col span={6}>
            <div style={{ display: 'flow-root' }}>
              <div style={{ marginRight: 8 }}>
                <div>设备动画（ZIP）</div>
              </div>
              <Form.Item style={{ marginBottom: 5, marginTop: 5 }}>
                <Upload
                  fileList={equipmentAnimationList}
                  accept=".zip"
                  maxCount={1}
                  onRemove={() => handleRemove('equipmentAnimation', setEquipmentAnimationList)}
                  beforeUpload={(file) => handleBeforeUpload(file, 'equipmentAnimation', setEquipmentAnimationList)}
                >
                  {equipmentAnimationList && equipmentAnimationList.length >= 1 ? (
                    <Button icon={<UploadOutlined />} size="small">已上传</Button>
                  ) : (
                    <Button type="primary" icon={<UploadOutlined />} size="small">上传动画包</Button>
                  )}
                </Upload>
                <div style={{ color: 'red', fontSize: 12, lineHeight: '13px' }}>仅允许上传 ZIP 压缩包</div>
              </Form.Item>
            </div>
          </Col>
          <Col span={6}>
            {renderPictureUpload('底部 Logo', 'homeDownImg', homeDownImgList, setHomeDownImgList, '.jpg,.png', '建议尺寸：130px × 52px', 5)}
          </Col>
        </Row>

        {/* 第三行：Logo 链接 */}
        <Row gutter={20} style={{ marginBottom: 10 }}>
          <Col span={12}>
            <Form.Item label="Logo 链接">
              <Input
                value={setting.logoUrl}
                placeholder="请输入点击 Logo 跳转的 URL"
                onChange={(e) => onInputChange('logoUrl', e)}
                autoComplete="off"
              />
            </Form.Item>
          </Col>
        </Row>

        {/* 底部文案（富文本编辑器） */}
        <Row gutter={20}>
          <Col span={24}>
            <Form.Item label="设备页面底部文案">
              <Space direction="vertical" style={{ width: '100%' }}>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleBold().run()} type={editor?.isActive('bold') ? 'primary' : 'default'}>
                    加粗
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleItalic().run()} type={editor?.isActive('italic') ? 'primary' : 'default'}>
                    斜体
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleUnderline().run()} type={editor?.isActive('underline') ? 'primary' : 'default'}>
                    下划线
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleStrike().run()} type={editor?.isActive('strike') ? 'primary' : 'default'}>
                    删除线
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().setParagraph().run()} type={editor?.isActive('paragraph') ? 'primary' : 'default'}>
                    段落
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()} type={editor?.isActive('heading', { level: 2 }) ? 'primary' : 'default'}>
                    H2
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleHeading({ level: 3 }).run()} type={editor?.isActive('heading', { level: 3 }) ? 'primary' : 'default'}>
                    H3
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleBulletList().run()} type={editor?.isActive('bulletList') ? 'primary' : 'default'}>
                    • 列表
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleOrderedList().run()} type={editor?.isActive('orderedList') ? 'primary' : 'default'}>
                    1. 列表
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleBlockquote().run()} type={editor?.isActive('blockquote') ? 'primary' : 'default'}>
                    引用
                  </Button>
                  <Button size="small" onClick={() => editor?.chain().focus().toggleCodeBlock().run()} type={editor?.isActive('codeBlock') ? 'primary' : 'default'}>
                    代码块
                  </Button>
                  <Button size="small" onClick={() => {
                    const prev = editor?.getAttributes('link')?.href || '';
                    const url = window.prompt('请输入链接地址：', prev);
                    if (url === null) return;
                    if (url === '') {
                      editor?.chain().focus().unsetLink().run();
                      return;
                    }
                    editor?.chain().focus().setLink({ href: url }).run();
                  }} type={editor?.isActive('link') ? 'primary' : 'default'}>
                    链接
                  </Button>
                </div>
                <div style={{ border: '1px solid #d9d9d9', borderRadius: 6, padding: 12, minHeight: 220, background: '#fff' }}>
                  <EditorContent editor={editor} />
                </div>
              </Space>
            </Form.Item>
          </Col>
        </Row>

        <Button type="primary" disabled={saving} onClick={submitForm} style={{ marginTop: 24 }}>
          保存
        </Button>
      </Form>

      <Modal open={tipsOpen} title="上传提示" onCancel={() => setTipsOpen(false)} onOk={() => setTipsOpen(false)}>
        <div style={{ whiteSpace: 'pre-line' }}>{tipsText}</div>
      </Modal>
    </Card>
  );
}